package com.hzit.ms.service.impl;

import com.hzit.ms.mapper.GoodsInfoMapper;
import com.hzit.ms.mapper.OrderInfoMapper;
import com.hzit.ms.mapper.SkOrderInfoMapper;
import com.hzit.ms.model.OrderInfo;
import com.hzit.ms.model.SkOrderInfo;
import com.hzit.ms.service.IOrderService;
import com.hzit.ms.vo.CreateOrderReqData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {


    @Autowired
    private SkOrderInfoMapper skOrderInfoMapper;

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;


    @Override
    @Transactional
    public void createOrder(CreateOrderReqData createOrderReqData) {

        //1.判断逻辑 TODO

        //2.创建订单，秒杀订单表，订单表
        Long orderId = System.currentTimeMillis(); //TODO 分布式的唯一id

        SkOrderInfo skOrderInfo = new SkOrderInfo();
        skOrderInfo.setUserId(Long.parseLong(createOrderReqData.getUserId()));
        skOrderInfo.setGoodsId(Long.parseLong(createOrderReqData.getGoodsId()));
        skOrderInfo.setOrderId(orderId);
        skOrderInfoMapper.insertSelective(skOrderInfo);


        OrderInfo orderInfo = new OrderInfo();
        Date date = new Date();
        orderInfo.setAddrId(100l);
        orderInfo.setCreateDate(date);;
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsName("测试");
        orderInfo.setGoodsPrice(new BigDecimal(1499)); //数据库的金额 用decimal

        orderInfoMapper.insertSelective(orderInfo);

        //3.减库存.避免超卖， 基于数据库的乐观锁
        goodsInfoMapper.updateStockByGoodsId(Integer.parseInt(createOrderReqData.getGoodsId()));


        //4.减秒杀库存



    }


    @Override
    public void queryOrderByUserIdAndGoodsId(String userId, String goodsId) {

        List<SkOrderInfo>  skOrderInfoList = skOrderInfoMapper.queryByUserIdAndGoodsId(userId,goodsId);

        if (CollectionUtils.isEmpty(skOrderInfoList)){

            // 返回0

            return;
        }

        //返回秒杀成功 1









    }
}
